<?php
namespace Admin\Controller;

/**
 * 新闻资讯管理
 * @author  liubo <liubo@ilongyuan.com.cn>
 */
class NewsController extends BaseManageController {
    /**
    *控制操作的模型表
    */
    protected $modelName = 'Common/News';

    /**
    *删除类型的设置 true|直接删除， false|设置数据状态
    */  
    protected $is_del   = false;

    /**
    *跳转的Url
    */
    protected $jumpAct  = 'News/index';

    /**
    *操作index的前置操作
    *---设置数据筛选条件---
    */
    public function _before_index()
    {
        $map = array();//筛选条件
        $map['status'] = array('egt',0);
        $search = trim(I('get.title', '', 'strip_tags'));
        if($search){
            $map['title'] = array('like', (string)$search);
        }
        $this->where = $map;
    }

    public function _before_add() {
        $this->assign('create_time', NOW_TIME);
        $this->_before_edit();

        if (!IS_POST){
            if (I('from_crawle')){
                $_id = I('from_crawle');
                $data = service('CrawleNewsOrigin')->find($_id);
                if ($data){
                    $assign = [
                        'title'   => $data['title'],
                        'content' => $this->crawle_parse($data['content_parsed']),
                        'author'  => $data['author'],
                        'from'    => $data['web_name'],
                        'create_time' => strtotime($data['date']),
                    ];
                    $this->assign($assign);
                }
                $this->assign('from_crawle', $_id);
            }
        }else{
            if (I('from_crawle')){
                $_id = I('from_crawle');
                service('CrawleNewsOrigin')->where(['_id' => new \MongoId($_id)])->save(['submited' => 1]);
            }
        }

    }

    protected function crawle_parse($html)
    {
        $data = explode('[/line]', $html);
        $content = [];
        foreach ($data as $line) {
            $line = trim($line);
            if (!$line) continue;
            if (strpos($line, '[img') === 0){
                preg_match('/\[img src="([^"]+)"\]/ius', $line, $matches);
                $src = $matches[1];
                $item = [
                    'type' => 'image',
                    'data' => [
                        'url'   => $src,
                        'scale' => '',
                    ],
                ];
            }else{
                $item = [
                    'type' => 'text',
                    'data' => [
                        'content' => $line
                    ],
                ];
            }
            $content[] = $item;
        }
        return $content;
    }

    public function _before_edit() {
        if (!IS_POST) {
            $games = event('game')->lists([], 'id,name');

            $mService = service('match');
            $map = ['status'=>$mService::STATUS_PASS];
            $orderby = 'match_state desc, create_time desc';
            $field = 'id,title,game_id';
            $matches = $mService->where($map)->field($field)->order($orderby)->select();

            $this->assign(['games' => $games, 'matches' => $matches]);
        }
    }

    // 添加
    public function add() {
        if (IS_POST) {
            $data = $this->model->create();
            if ($data) {
                unset($data['id']);
            }
            $data['content'] = $this->format_content($data['content']);
            $data['create_time'] = strtotime($data['create_time']);
            if ($data && $id = $this->model->add($data)) {
                if ($data['type'] == 0) {
                    $data['id'] = $id;
                    // 上报新闻资源
                    event('ResourceGroup')->storeNews($data);
                }
                // 删除了jumpAct调用U函数  ini里已经做了
                $this->success('操作成功!', $this->jumpAct);
            } else {
                $this->error($this->model->getError());
            }
        } else {
            $this->display('form');
        }
    }

    // 编辑
    public function edit($id) {
        $id = I('id', 0, 'intval');
        $this->model->id = $this->id = $id;
        if (IS_POST) {
            $data = I('');
            $data['id'] = $id;
            $data = $this->model->create($data);
            unset($data['id']);
            $data['content'] = $this->format_content($data['content']);
            $data['create_time'] = strtotime($data['create_time']);
            $map = array('id' => $id);
            if ($data && $this->model->where($map)->save($data)) {
                // 更新新闻资源
                event('ResourceGroup')->updateNews($id);

                $this->success('操作成功!', $this->jumpAct);
            } else {
                $this->error($this->model->getError());
            }
        } else {
            $data[] = $this->model->find($id);
            int_to_string($data, $this->text_map);
            $this->assign($data[0]);
            $this->display('form');
        }
    }

    public function push($id)
    {
        $id = intval($id);

        $nService = service('news');
        $data = $nService->find($id);

        if (empty($data)) {
            $this->error('非法操作项');
        }

        if (IS_POST) {
            $msg = I('msg', '', 'trim');
            if (empty($msg)) {
                $this->error('推送消息不能为空');
            }
            $plat = I('plat');

            event('Push')->notice($id, $msg, $plat);
            $this->success('推送完成');
        } else {
            $this->assign($data);
            $this->display();
        }
    }

    private function format_content($content) {
        foreach ($content as &$value) {
            switch ($value['type']) {
                case 'text':
                    $value['data']['bold'] = intval($value['data']['bold']);
                    break;
                case 'video':
                    $value['data']['id'] = intval($value['data']['id']);
                    break;
            }
        }
        return $content;
    }

    public function _after_editRow($id, $data)
    {
        event('ResourceGroup')->updateNews($id);
    }
}